<!-- 用户curd -->
<template>
    <div class="app-container">
        昵称:
        <el-input
            style="width: 10%"
            v-model="pageUser.nickname"
            placeholder="用户名"
            autofocus="true"
            maxlength="10"
        ></el-input>性别:
        <el-select style="width: 10%" v-model="pageUser.sex" clearable placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
        </el-select>年龄:
        <el-input-number
            style="width: 10%"
            v-model="pageUser.lowAge"
            :min="0"
            controls-position="right"
        ></el-input-number>-
        <el-input-number
            style="width: 10%"
            v-model="pageUser.highAge"
            :min="0"
            controls-position="right"
        ></el-input-number>注册时间:
        <el-date-picker
            v-model="pageUser.time"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
        <el-button type="primary" @click="getUsers">查询</el-button>
        <br />
        <el-button type="success" @click="$router.push({
            name: 'userInfo'
        })">添加</el-button>
        <el-button
            type="danger"
            :disabled="deleteBatchButton"
            @click="deleteByIds(multipleSelection)"
        >批量删除</el-button>

        <el-divider></el-divider>
        <!--*****************************表格数据****************************-->
        <el-table
            :data="users"
            style="width: 100%"
            v-loading="loading"
            stripe
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="头像">
                <template slot-scope="scope">
                    <!-- <el-avatar shape="square" :size="medium" :src="scope.row.avatar"></el-avatar> -->
                    <el-avatar :size="45" fit="fill" :src="scope.row.avatar"></el-avatar>
                </template>
            </el-table-column>
            <el-table-column label="昵称" width="150" fixed>
                <template slot-scope="scope">
                    <el-tag>{{ scope.row.nickname }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="性别">
                <template slot-scope="scope">
                    <el-tag type="info">{{ scope.row.sex == 1 ? "女" : "男" }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄"></el-table-column>
            <el-table-column prop="sign" label="个性签名"></el-table-column>
            <el-table-column prop="gmtCreate" width="150" label="注册日期"></el-table-column>
            <el-table-column label="是否封禁">
                <template slot-scope="scope">
                    <el-switch
                        style="display: block"
                        v-model="scope.row.isDisabled"
                        active-color="#ff4949"
                        inactive-color="#13ce66"
                        active-text="封禁"
                        inactive-text="不封禁"
                        @change="changeDisabled(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="230">
                <template slot-scope="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click="$router.push({
                        name: 'userInfo',
                        params: { 'id': scope.row.id }
                    })"
                    >修改</el-button>
                    <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
                    <el-tooltip content="分配角色" placement="bottom" effect="light">
                        <el-button
                            type="info"
                            size="small"
                            icon="el-icon-info"
                            @click="endowedUserRole(scope.row.id)"
                        ></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!--******************************给用户分配角色对话框*********************-->
        <!-- Form -->
        <el-dialog title="给用户分配角色" :visible.sync="dialogFormVisible" @close="closeDialog()">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="role.searchObj.roleName" placeholder="角色名称" />
                </el-form-item>

                <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
                <el-button type="default" @click="resetData()">清空</el-button>
            </el-form>
            <!-- 角色列表 -->
            <el-table
                v-loading="role.listLoading"
                :data="role.list"
                ref="multipleTable"
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange2"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="70" align="center">
                    <template
                        slot-scope="scope"
                    >{{ (role.page - 1) * role.limit + scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column prop="roleName" label="角色名称" />
            </el-table>

            <!-- 分页组件 -->
            <el-pagination
                :current-page="role.page"
                :total="role.total"
                :page-size="role.limit"
                :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
                style="padding: 30px 0; text-align: center;"
                layout="sizes, prev, pager, next, jumper, ->, total, slot"
                @current-change="fetchData"
                @size-change="changeSize"
            />
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false;userRole.roleIds=[]">取 消</el-button>
                <el-button type="primary" @click="getUserRole()">分 配</el-button>
            </div>
        </el-dialog>

        <!--****************************分页器**********************************-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page="current"
            :page-sizes="[6, 15, 20, 30, 40, 50]"
            :page-size="limit"
            :hide-on-single-page="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>

        <el-backtop :visibility-height="100"></el-backtop>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { pageUser, removeByIds, updateUser } from "@/api/ucenter/user";
import roleApi from "@/api/acl/role";
export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        //这里存放数据
        return {
            pageUser: {
                nickname: "",
                sex: "",
                lowAge: 0,
                highAge: 100,
                beginTime: "",
                endTime: "",
                time: [],
            },
            current: 1,
            limit: 6,
            total: 0,
            options: [
                {
                    value: "1",
                    label: "女",
                },
                {
                    value: "2",
                    label: "男",
                },
            ],
            users: [],
            loading: true,
            multipleSelection: [],
            deleteBatchButton: true,
            dialogFormVisible: false,
            userRole: {
                userId: "",
                roleIds: [],
            },
            role: {
                listLoading: true, // 数据是否正在加载
                list: null, // 角色列表
                total: 0, // 数据库中的总记录数
                page: 1, // 默认页码
                limit: 10, // 每页记录数
                searchObj: {}, // 查询表单对象
                multipleSelection: [], // 批量选择中选择的记录列表
            },
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        getUsers() {
            if (this.pageUser.time) {
                this.pageUser.beginTime = this.pageUser.time[0];
                this.pageUser.endTime = this.pageUser.time[1];
            } else {
                this.pageUser.beginTime = "";
                this.pageUser.endTime = "";
            }
            pageUser(this.pageUser, this.current, this.limit).then(
                (response) => {
                    this.users = response.data.users;
                    this.total = response.data.rows;
                    this.loading = false;
                }
            );
        },
        handleSizeChange(val) {
            this.loading = true;
            this.current = parseInt((this.current * this.limit) / val);
            this.limit = val;
            this.getUsers();
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.current = val;
            this.getUsers();
        },
        handleSelectionChange(val) {
            this.deleteBatchButton = val.length === 0 ? true : false;
            this.multipleSelection = [];
            for (var i = 0; i < val.length; i++) {
                this.multipleSelection.push(val[i].id);
            }
        },
        deleteById(id) {
            var ids = [];
            ids.push(id);
            this.deleteByIds(ids);
        },
        deleteByIds(ids) {
            this.$confirm("确定要删除吗?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                removeByIds(ids)
                    .then((response) => {
                        this.getUsers();
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                    })
                    .catch(() => {});
            });
        },
        changeDisabled(user) {
            updateUser(user).then((response) => {
                this.$message({
                    message: "成功",
                    type: "success",
                });
            });
        },
        //给用户分配角色
        getUserRole() {
            roleApi
                .endowedUserRole(this.userRole.userId, this.userRole.roleIds)
                .then((response) => {
                    this.$message({
                        message: "分配成功",
                        type: "success",
                    });
                    this.userRole.roleIds = [];
                    this.dialogFormVisible = false;
                    this.toggleSelection();
                });
        },
        fetchData(page = 1) {
            this.role.page = page;
            roleApi
                .page(this.role.page, this.role.limit, this.role.searchObj)
                .then((response) => {
                    this.role.list = response.data.roles;
                    this.role.total = response.data.rows;
                    this.role.listLoading = false;
                });
        },
        // 重置查询表单
        resetData() {
            this.role.searchObj = {};
            this.fetchData();
        },
        changeSize(size) {
            this.role.limit = size;
            this.fetchData(1);
        },
        handleSelectionChange2(selection) {
            this.userRole.roleIds = [];
            for (let i = 0; i < selection.length; i++) {
                this.userRole.roleIds.push(selection[i].id);
            }
        },
        endowedUserRole(userId) {
            roleApi.getUserRole(userId).then((response) => {
                this.dialogFormVisible = true;
                this.userRole.userId = userId;
                let ids = response.data.roleIds;
                let tmp = [];
                for (let i = 0; i < ids.length; i++) {
                    for (let j = 0; j < this.role.list.length; j++) {
                        if (ids[i] === this.role.list[j].id) {
                            tmp.push(this.role.list[j]);
                        }
                    }
                }
                this.toggleSelection(tmp);
            });
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach((row) => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        closeDialog() {
            this.userRole.roleIds = [];
            this.toggleSelection();
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.fetchData();
        this.dialogFormVisible = true;
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        this.getUsers();
        this.dialogFormVisible = false;
    },
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发，页面一旦激活就会触发
};
</script>
<style scoped>
</style>